package com.quanyan.stadium.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.gson.Gson;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.RespClubPlainInfo;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.vo.Image;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.stadium.api.req.*;
import com.quanyan.stadium.api.req.v2.ReqUpdateOpponent;
import com.quanyan.stadium.api.resp.*;
import com.quanyan.stadium.api.resp.v2.RespClubAbstract;
import com.quanyan.stadium.api.resp.v2.RespClubMsg;
import com.quanyan.stadium.api.resp.v2.RespGameSystem;
import com.quanyan.stadium.api.resp.v2.RespGameSystemAndUserClubMsg;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.biz.redis.GameCacheDao;
import com.quanyan.stadium.component.cache.MyRedisTemplate;
import com.quanyan.stadium.component.cache.StadiumRedisConstants;
import com.quanyan.stadium.component.pushMsg.MsgPush;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.*;
import com.quanyan.stadium.enums.errorEnum.CreateCompListErrorEnum;
import com.quanyan.stadium.enums.errorEnum.RecordScoreErrorEnum;
import com.quanyan.stadium.mapper.TbGameEventMapper;
import com.quanyan.stadium.mapper.TbGameEventTeamMapper;
import com.quanyan.stadium.mapper.TbGameScheduleAddendumMapper;
import com.quanyan.stadium.mapper.TbGameScheduleMapper;
import com.quanyan.stadium.service.GameEventService;
import com.quanyan.stadium.service.commonComponent.*;
import com.quanyan.stadium.service.gameEvent.ClubGameEventConfigService;
import com.quanyan.stadium.service.gameRules.GameRoundService;
import com.quanyan.stadium.service.gameRules.GameScheduleService;
import com.quanyan.stadium.service.gameSign.GameSignUpService;
import com.quanyan.stadium.transfer.GameConfigTransfer;
import com.quanyan.stadium.utils.GameUtils;
import com.quanyan.statium.api.req.GameCategory;
import com.quanyan.statium.api.req.GameGradeLevel;
import com.quanyan.statium.api.req.PayTypeModel;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author xiaoxiao
 * @date 16/4/11-14:42
 */

@Service("gameEventService")
public class GameEventServiceImpl implements GameEventService {

    private final static Logger logger = LoggerFactory.getLogger(GameEventServiceImpl.class);

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private GameRoundService gameRoundService;

    @Autowired
    private GameScheduleService gameScheduleService;

    @Autowired
    private BaseService baseService;

    @Autowired
    private DataReductionService dataReductionService;

    @Autowired
    private ClubGameEventConfigService clubGameEventConfigService;

    @Autowired
    private GameSignUpService gameSignUpService;

    @Autowired
    private OfficialGameCache officialGameCache;

    @Autowired
    private GameMQProduct gameMQProduct;

    @Autowired
    private GameMsgPush gameMsgPush;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private TbGameEventMapper tbGameEventMapper;

    @Autowired
    private TbGameScheduleMapper tbGameScheduleMapper;

    @Autowired
    private TbGameEventTeamMapper tbGameEventTeamMapper;

    @Autowired
    private TbGameScheduleAddendumMapper tbGameScheduleAddendumMapper;

    @Autowired
    private GameCacheDao gameCacheDao;

    @Autowired
    private GameConfigTransfer gameEventTransfer;



    @Override
    public APIResponse finishGameRound(ReqFinishGameEvent reqFinishGameEvent, Integer uid) {
        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(reqFinishGameEvent.getGameEventId());
        Collections.sort(tbGameRoundList, new Comparator<TbGameRound>() {   //按轮次的先后排序,id最大的为最后一轮
            public int compare(TbGameRound o1, TbGameRound o2) {
                return o2.getId().compareTo(o1.getId());
            }
        });
        TbGameRound currentRound = tbGameRoundList.get(0);
        if (!currentRound.getId().equals(reqFinishGameEvent.getCurrentRoundId())) {
            //校验上一轮的赛程是否录入全部有效(冲突时候停止,其他情况返回)
            List<TbGameSchedule> tbGameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(reqFinishGameEvent.getCurrentRoundId(), null, null);
            for (TbGameSchedule tbGameSchedule : tbGameScheduleList) {
                if (tbGameSchedule.getStatus().intValue() == GameConstants.RECORD_FAIL.intValue() ||
                        tbGameSchedule.getStatus().intValue() == GameConstants.RECORD_WAIT.intValue() ||
                        tbGameSchedule.getStatus().intValue() == GameConstants.RECORD_WAIT_SURE.intValue()) {
                    return APIResponse.returnFail(CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_11.getLabel());
                }
                tbGameSchedule.setStatus(GameConstants.RECORD_SUCCESS);
                bizGameSystemDao.updateTbGameSchedule(tbGameSchedule);
            }

            //更新轮次结束
            TbGameRound preGameRound = new TbGameRound();
            preGameRound.setId(reqFinishGameEvent.getCurrentRoundId());
            preGameRound.setIsEnd(GameConstants.IS_DELETE);
            bizGameSystemDao.updateTbGameRound(preGameRound);

            officialGameCache.delGameRound(reqFinishGameEvent.getCurrentRoundId());

            return APIResponse.returnSuccess();
        }
        return this.finishGameEvent(reqFinishGameEvent, uid);
    }

    @Override
    public  APIResponse finishGameEvent(ReqFinishGameEvent reqFinishGameEvent, Integer uid) {
        //TODO redis 操作迁移到redis dao中处理
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getGameEventFinishKey(reqFinishGameEvent.getGameEventId()));
        long flag = myRedisTemplate.setnx(redisKey);
        if (flag == 0) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事完结处理中,请不要重复操作");
        }
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(reqFinishGameEvent.getGameEventId());
        if (gameEvent.getCurrentRoundId() == -1) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事已完结,无法操作");
        }
        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEvent.getId());
        Collections.sort(tbGameRoundList, new Comparator<TbGameRound>() {   //按轮次的先后排序,id最大的为最后一轮
            public int compare(TbGameRound o1, TbGameRound o2) {
                return o2.getId().compareTo(o1.getId());
            }
        });
        TbGameRound currentRound = tbGameRoundList.get(0);
        if (!currentRound.getId().equals(reqFinishGameEvent.getCurrentRoundId())) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("未到最后轮次,赛事无法完结");
        }
        List<TbGameSchedule> tbGameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(reqFinishGameEvent.getCurrentRoundId(), null, null);
        for (TbGameSchedule tbGameSchedule : tbGameScheduleList) {
            if (tbGameSchedule.getStatus() != GameConstants.RECORD_SUCCESS) {
                myRedisTemplate.delteKey(redisKey);
                return APIResponse.returnFail("当前轮次中存在未录入比分的赛程,请先录入比分,完成赛程");
            }
        }

        //录入积分
        if (!gameScheduleService.recordGameRoundTeamScore(gameEvent, currentRound.getId(), tbGameRoundList, null)) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("当前轮次未产生有效的积分,无法完结比赛");
        }


        //MQ, 赛事完结的时候, 参数1和2是一样的
        dataReductionService.generateCurrentRoundMQ(currentRound, currentRound, gameEvent, true);

        TbGameRound tbGameRound = new TbGameRound();
        tbGameRound.setId(reqFinishGameEvent.getCurrentRoundId());
        tbGameRound.setIsEnd(GameConstants.IS_DELETE);
        bizGameSystemDao.updateTbGameRound(tbGameRound);             //更新轮次为结束

        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setId(reqFinishGameEvent.getGameEventId());
        tbGameEvent.setCurrentRoundId(-1);   //赛事结束
        bizGameSystemDao.updateTbGameEvent(tbGameEvent);            //更新赛事为结束

        if (gameEvent.getType().intValue() == GameConstants.IS_DELETE.intValue() && null!=gameEvent.getClubId()) {
            gameSignUpService.setterUp(tbGameEvent.getId());        //俱乐部比赛调起结算
        }

        officialGameCache.delGameRound(currentRound.getId());       //清空当前轮次
        officialGameCache.delGameEvent(gameEvent.getId());    //清空当前赛事

        myRedisTemplate.delteKey(redisKey);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse finishGameEvent(Integer gameEventId) {
        //TODO redis 操作迁移到redis dao中处理
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getGameEventFinishKey(gameEventId));
        long flag = myRedisTemplate.setnx(redisKey);
        if (flag == 0) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事完结处理中,请不要重复操作");
        }
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (gameEvent.getCurrentRoundId() == -1) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事已完结,无法操作");
        }

        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setId(gameEventId);
        tbGameEvent.setCurrentRoundId(-1);   //赛事结束
        bizGameSystemDao.updateTbGameEvent(tbGameEvent);            //更新赛事为结束

        if (gameEvent.getType().intValue() == GameConstants.IS_DELETE.intValue() && null!=gameEvent.getClubId()) {
            gameSignUpService.setterUp(tbGameEvent.getId());        //俱乐部比赛调起结算
        }

        officialGameCache.delGameEvent(gameEvent.getId());    //清空当前赛事

        myRedisTemplate.delteKey(redisKey);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse finishPersonaPersonalGameEvent(ReqFinishGameEvent reqFinishGameEvent, Integer uid,Boolean isEffective) {
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getGameEventFinishKey(reqFinishGameEvent.getGameEventId()));
        long flag = myRedisTemplate.setnx(redisKey);
        if (flag == 0) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事完结处理中,请不要重复操作");
        }
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(reqFinishGameEvent.getGameEventId());

        if (gameEvent.getCurrentRoundId() == -1) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnFail("赛事已完结,无法操作");
        }
        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEvent.getId());
        TbGameRound currentRound = tbGameRoundList.get(0);
        //MQ, 赛事完结的时候, 参数1和2是一样的
        if(isEffective) {
            gameMQProduct.gameScheduleEndScoreGradeMQ(gameEvent, currentRound);
            gameMQProduct.gameEventFinish(gameEvent, currentRound);
            logger.info("推送个人赛结束消息，赛事Id:"+gameEvent.getId());
        }

        TbGameRound tbGameRound = new TbGameRound();
        tbGameRound.setId(reqFinishGameEvent.getCurrentRoundId());
        tbGameRound.setIsEnd(GameConstants.IS_DELETE);
        bizGameSystemDao.updateTbGameRound(tbGameRound);             //更新轮次为结束

        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setId(reqFinishGameEvent.getGameEventId());
        tbGameEvent.setCurrentRoundId(-1);   //赛事结束
        bizGameSystemDao.updateTbGameEvent(tbGameEvent);            //更新赛事为结束

        officialGameCache.delGameRound(currentRound.getId());       //清空当前轮次
        officialGameCache.delGameEvent(gameEvent.getId());    //清空当前赛事

        logger.info("个人赛成功结束：gameEventId:" + reqFinishGameEvent.getGameEventId() + ";currentRoundId:" + reqFinishGameEvent.getCurrentRoundId() + "------------");
        myRedisTemplate.delteKey(redisKey);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse cancelClubGameEvent(Integer gameEventId) {
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);

        if (gameEvent.getGameEventType().intValue() != GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId()) {
            return APIResponse.returnFail("该俱乐部没有权限无法取消比赛");
        }
        if ((new Date()).after(gameEvent.getSignStartTime()) && new Date().before(gameEvent.getSignEndTime())) {
            return APIResponse.returnFail("活动处于报名阶段,无法取消比赛");
        }
        if (null!=gameEvent.getCurrentRoundId()) {
            if(gameEvent.getCurrentRoundId().intValue() != 0) {
                if (gameEvent.getCurrentRoundId().intValue() == -1) {
                    return APIResponse.returnFail("赛事已经完结,无法取消比赛");
                }else {
                    return APIResponse.returnFail("赛事已处于进行中,无法取消比赛");
                }
            }
        }
        if (bizGameSystemDao.cancelGameEvent(gameEventId).getId() < 1) {
            return APIResponse.returnFail("取消比赛失败");
        }
        try{
            gameSignUpService.refound(gameEventId);
        }catch (Exception e)  {
            logger.error("赛事退款失败, 当前赛事ID:{}", gameEventId);
        }
        logger.info("赛事取消调起退款流程,当前赛事Id:{}", gameEventId);

        List<TbGameEventTeam> totalTeams = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEvent.getId(), GameConstants.IS_NOT_DELETE);
        if (totalTeams!=null && totalTeams.size() >0) {
            List<Integer> totalUids = new ArrayList<>();
            if (gameEvent.getGameTeamType().equals(GameConstants.TEAM_TYPE_CLUB)) {   //俱乐部
                List<Integer> clubIds = new ArrayList<>();
                for (TbGameEventTeam tb:totalTeams) {
                    clubIds.add(tb.getClubId());
                }
                Map<Integer ,List<Integer>> clugUIds = baseService.queryClubIds(clubIds);
                for (TbGameEventTeam tb:totalTeams) {
                    totalUids.addAll(clugUIds.get(tb.getClubId()));
                }
            }else { //个人
                for (TbGameEventTeam tb:totalTeams) {
                    totalUids.add(tb.getUid());
                }
            }
            if (totalUids!=null && totalUids.size()>0) {    //推送消息
                gameMsgPush.pushGameCancelMsgToUser(totalUids, gameEvent);
            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<List<GameEvent>> getClubPlaceGameEventList(Integer clubId, Integer districtId, Integer categoryId) throws InvocationTargetException, IllegalAccessException {
        /*List<TbGameClubOfficial> msg = bizGameSystemDao.queryTbGameOfficialClubList(clubId, categoryId);
        if (null == msg || msg.size()<1) {
            return APIResponse.returnFail("不存在授权场馆");
        }
        Set<Integer> placeIds = new HashSet<>();
        for (TbGameClubOfficial tbGameOfficialClub : msg) {  //授权场馆集合
            placeIds.add(tbGameOfficialClub.getPlaceId());
        }*/

        List<TbGameEvent> tbGameEvents = bizGameSystemDao.selectTbGameEventPlaces(null, districtId, categoryId);
        if (null == tbGameEvents || tbGameEvents.size() < 1) {
            return APIResponse.returnSuccess(null);
        }
        Set<Integer> placeIds = new HashSet<>();
        for (TbGameEvent tbGameEvent : tbGameEvents) {
            placeIds.add(tbGameEvent.getPlaceId());
        }
        Map<Integer, PlaceInfo> placeMap = baseService.queryPlaceInfoMsgList(new ArrayList<Integer>(placeIds));
        List<GameEvent> result = new ArrayList<>();
        for (TbGameEvent tbGameEvent : tbGameEvents) {
            GameEvent gameEvent = new GameEvent();
            gameEvent.setId(tbGameEvent.getId());
            gameEvent.setName(tbGameEvent.getName());
            gameEvent.setPlaceInfo(placeMap.get(tbGameEvent.getPlaceId()));
            result.add(gameEvent);
        }
        return APIResponse.returnSuccess(result);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<GameEvent> clubCreateGameEvent(Integer uid, ReqCreateClubGameEvent createIntegrateGame) throws InvocationTargetException, IllegalAccessException {
        TbGameEvent parentGameEvent = bizGameSystemDao.selectTbGameEvent(createIntegrateGame.getParentId());
       /* List<TbGameClubOfficial> msg = bizGameSystemDao.queryTbGameOfficialClubList(createIntegrateGame.getClubId(), createIntegrateGame.getCategoryId());
        if (null == msg || msg.size()<1) {
            return APIResponse.returnFail("不存在授权场馆");
        }
        boolean isAuthorize = false;
        for (TbGameClubOfficial tbGameOfficialClub : msg) {
            if (tbGameOfficialClub.getPlaceId().equals(parentGameEvent.getPlaceId()) &&
                    (createIntegrateGame.getStartTime() > tbGameOfficialClub.getSignStartTime().getTime() && createIntegrateGame.getEndTime() < tbGameOfficialClub.getSignExpireTime().getTime())) {
                isAuthorize = true;
                break;
            }
        }
        if (!isAuthorize) {
            return APIResponse.returnFail("该场馆在该时间段内未被授权");
        }*/
        //时间校验
        if (createIntegrateGame.getSignStartTime() >= createIntegrateGame.getSignEndTime() || createIntegrateGame.getStartTime()>=createIntegrateGame.getEndTime() ||
                createIntegrateGame.getSignEndTime()>createIntegrateGame.getStartTime()) {
            return APIResponse.returnFail("时间参数不合法");
        }

        if (null == parentGameEvent) {
            return APIResponse.returnFail(ErrorEnum.ERROR_DB.getId(), ErrorEnum.ERROR_DB.getLabel());
        }
        if (null != createIntegrateGame.getGameCategoryType()
                && createIntegrateGame.getTeamLimitNum()%2 !=0) {
            return APIResponse.returnFail("双打时,队伍人数设置必须为偶数");
        }
        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setName(parentGameEvent.getName().replaceAll("决赛", "排位"));
        tbGameEvent.setPrice(createIntegrateGame.getPrice());
        tbGameEvent.setStartTime(new Date(createIntegrateGame.getStartTime()));
        tbGameEvent.setEndTime(new Date(createIntegrateGame.getEndTime()));
        tbGameEvent.setSignStartTime(new Date(createIntegrateGame.getSignStartTime()));
        tbGameEvent.setSignEndTime(new Date(createIntegrateGame.getSignEndTime()));
        tbGameEvent.setCategoryId(createIntegrateGame.getCategoryId());
        tbGameEvent.setPlaceId(parentGameEvent.getPlaceId());
        tbGameEvent.setCityId(parentGameEvent.getCityId());
        tbGameEvent.setDistrictId(parentGameEvent.getDistrictId());
        tbGameEvent.setType(GameConstants.CLUB_CREATE);
        tbGameEvent.setUid(uid);
        tbGameEvent.setClubId(createIntegrateGame.getClubId());
        tbGameEvent.setGameSystemType(createIntegrateGame.getGameSystemType().byteValue());
        tbGameEvent.setGameEventType((byte)GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId());
        tbGameEvent.setIsVisible(createIntegrateGame.getIsVisible().byteValue());

        if (null!=createIntegrateGame.getGameGradeLevel()) {
            tbGameEvent.setGameGradeLevelType(createIntegrateGame.getGameGradeLevel());
        }
        if (createIntegrateGame.getTeamLimitNum() == 0) {
            tbGameEvent.setTeamLimitNum(Integer.MAX_VALUE);
            tbGameEvent.setInventoryLevel(Integer.MAX_VALUE);
        }else {
            tbGameEvent.setTeamLimitNum(createIntegrateGame.getTeamLimitNum());
            tbGameEvent.setInventoryLevel(createIntegrateGame.getTeamLimitNum());
        }
        tbGameEvent.setGameDesc(createIntegrateGame.getBodyDesc());
        tbGameEvent.setParentId(parentGameEvent.getId());
        if (null != createIntegrateGame.getGameCategoryType()) {
            tbGameEvent.setGameCategoryType(createIntegrateGame.getGameCategoryType());
        }
        Gson gson =new Gson();
        RespClubPlainInfo club = baseService.queryClubMsg(createIntegrateGame.getClubId());
        MultiMedia multiMedia = new MultiMedia();
        Image image = new Image();
        if(null!=club){
            image.setImageUrl(club.getLogo());
            tbGameEvent.setManagerName(club.getClubName());
        }else{
            TbGameCommonParameter name = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                GameConstants.BASE_CONFIG_KEY_OFFICIAL_HOST_NAME);
            TbGameCommonParameter icon = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                GameConstants.BASE_CONFIG_KEY_OFFICIAL_HOST_ICON);
            image.setImageUrl(icon.getParameterValue());
            tbGameEvent.setManagerName(name.getParameterValue());
        }
        multiMedia.setType(GameConstants.IS_NOT_DELETE);   //图片
        multiMedia.setImage(image);
        tbGameEvent.setMultiMedia(gson.toJson(multiMedia));

        String gameCode = GameUtils.generateGameCode((byte)GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId(), createIntegrateGame.getCategoryId(), parentGameEvent.getPlaceId(), createIntegrateGame.getGameSystemType().byteValue());
        tbGameEvent.setGameNumber(gameCode);
        tbGameEvent = bizGameSystemDao.insertTbGameEvent(tbGameEvent);
        if (null == tbGameEvent.getId()) {
            return APIResponse.returnFail(ErrorEnum.ERROR_DB.getId(), ErrorEnum.ERROR_DB.getLabel());
        }
        logger.info("俱乐部创建赛事成功.俱乐部ID:{},赛事ID{}", createIntegrateGame.getClubId(), tbGameEvent.getId());
        GameEvent event = new GameEvent();
        event.setId(tbGameEvent.getId());
        event.setName(tbGameEvent.getName());
        event.setGameNumber(gameCode);
        TbGameCommonParameter tbGameCommonParameter = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_PARAMETER_KEY,
                MsgPush.GAME_OFFICIAL_EVENT_SHARE_MSG);
        event.setShareMsg(MsgPush.msgUtils(tbGameCommonParameter.getParameterValue(), tbGameEvent.getName()));  //分享

        gameMQProduct.clubCreateGameToUserCenterMQ(tbGameEvent, uid);
        gameMQProduct.clubCreateGameToClubMQ(tbGameEvent, uid, createIntegrateGame.getClubId());

        officialGameCache.getGameEvent(event.getId());
        logger.info("俱乐部创建赛事成功,开始缓存赛事信息.俱乐部ID:{},赛事ID{}", createIntegrateGame.getClubId(), tbGameEvent.getId());

        return APIResponse.returnSuccess(event);
    }


    @Override
    public APIResponse<RespGameSystemAndGameCategory> gameCategoryAndSystem(Integer categoryId, Byte gameType) {
        List<GameSystemConfigEnum> systems = new ArrayList<>();
        List<GameCategoryConfigEnum> categories = new ArrayList<>();
        List<GameGradeLevelConfigEnum> gradeLevels = new ArrayList<>();
        List<PayTypeEnum> payTypes = new ArrayList<>();
        switch(categoryId) {
            case 3:  //足球
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_WASHED);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_CIRCLE);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED);

                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V5);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V7);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V9);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V11);

                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_0);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_1);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_2);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_3);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_4);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_6);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_7);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_8);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_9);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_10);

                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_AA);
                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ME);
                break;
            case 1:  //篮球
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_WASHED);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_CIRCLE);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED);

                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V3);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V4);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V5);

                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_0);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_1);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_2);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_3);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_4);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_6);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_7);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_8);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_9);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_10);

                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_AA);
                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ME);
                break;
            case 4:  //网球
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_WASHED);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_CIRCLE);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE);

                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MALE_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_FEMALE_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MALE_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_FEMALE_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MIXED_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8);

                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_0);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_1);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_1_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_2);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_2_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_3);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_3_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_4);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_4_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_5_5);

                if (gameType.intValue() == GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId()) {
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_FREE);
                }else {
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_AA);
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ME);
                }
                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ONLINE);
                break;
            case 2:  //羽毛球
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_WASHED);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_CIRCLE);
                systems.add(GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE);

                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MALE_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_FEMALE_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MALE_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_FEMALE_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MIXED_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8);

                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_0);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_1);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_2);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_3);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_4);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_5);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_6);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_7);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_8);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_9);
                gradeLevels.add(GameGradeLevelConfigEnum.CONFIG_GAME_GRADE_LEVEL_10);

                if (gameType.intValue() == GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId()) {
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_FREE);
                }else {
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_AA);
                    payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ME);
                }
                payTypes.add(PayTypeEnum.CONFIG_PAY_TYPE_ONLINE);
                break;
            default:
                logger.debug("非四大球,栏目id异常");
        }

        return APIResponse.returnSuccess(this.generateGameSystemAndGameCategory(categories, systems, gradeLevels, payTypes, categoryId));
    }

    @Override
    public List<RespGameSystem> gameCategoryAndSystemV2(Integer categoryId) {
        Map<GameSystemConfigEnum, List<GameCategoryConfigEnum>> params = new HashMap<>();
        List<GameCategoryConfigEnum> categories = new ArrayList<>();
        List<GameCategoryConfigEnum> temp = new ArrayList<>();
        switch(categoryId) {
            case 3:  //足球
                break;
            case 1:  //篮球
                break;
            case 4:  //网球
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE);
                params.put(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS, categories);

                temp.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8);
                params.put(GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE, temp);
                break;
            case 2:  //羽毛球
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY);
                categories.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE);
                params.put(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS, categories);

                temp.add(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8);
                params.put(GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE, temp);
                break;
            default:
                logger.debug("非四大球,栏目id异常");
        }

        return this.generateGameSystemAndGameCategoryV2(params);
    }

    @Override
    public RespGameSystemAndUserClubMsg getGameSystemAndUserClubMsg(Integer categoryId, Integer uid) {
        List<RespGameSystem> gameSystemList = this.gameCategoryAndSystemV2(categoryId);
        Map<Integer, List<RespClubAbstract>> userClubMsg = this.getUserClubMsg(uid);
        RespGameSystemAndUserClubMsg result = new RespGameSystemAndUserClubMsg();
        List<RespClubMsg> respClubMsgs = new ArrayList<>();
        if(null != userClubMsg && userClubMsg.size() > 0) {
            for (Map.Entry<Integer, List<RespClubAbstract>> entry : userClubMsg.entrySet()) {
                int category = entry.getKey();
                if(category == GameConstants.CATEGORY_ID_BADMINTON || category == GameConstants.CATEGORY_ID_TENNIS ){
                    String categoryName = GameCategoryEnum.getMsgById(category).getName();
                    List<RespClubAbstract> respClubAbstracts = entry.getValue();
                    RespClubMsg clubMsg = new RespClubMsg();
                    clubMsg.setCategoryId(category);
                    clubMsg.setCategoryName(categoryName);
                    clubMsg.setClubAbstractList(respClubAbstracts);
                    respClubMsgs.add(clubMsg);
                }
            }
        }
        result.setRespGameSystemList(gameSystemList);
        result.setRespClubMsgs(respClubMsgs);
        return result;
    }


    @Override
    public APIResponse<RespGameRoundAndGameTeam> updateGroupNumAndRankNum(ReqGroupNumAndRankNum reqGroupNumAndRankNum) throws Exception {
        if (GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED.getId() != reqGroupNumAndRankNum.getGameSystemType().intValue()) {  //赛制类型校验
            return APIResponse.returnFail("该赛事赛制类型不合法");
        }
        //分组限制为1次
        List<TbGameRound> rounds = bizGameSystemDao.selectTbGameRoundByGameEventId(reqGroupNumAndRankNum.getGameEventId());
        if (null != rounds && rounds.size() > 0) {
            return APIResponse.returnFail("不能重复分组");
        }
        //校验两个值大小
        RespGameRoundAndGameTeam respGameRoundAndGameTeam = new RespGameRoundAndGameTeam();
        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setId(reqGroupNumAndRankNum.getGameEventId());
        tbGameEvent.setTeamGroupNum(reqGroupNumAndRankNum.getGroupNum());
        tbGameEvent.setRankNum(reqGroupNumAndRankNum.getRankNum());
        TbGameEvent gameEventTemp = bizGameSystemDao.updateTbGameEvent(tbGameEvent);
        if (null == gameEventTemp.getId()) {
            return APIResponse.returnFail(ErrorEnum.ERROR_DB.getId(), ErrorEnum.ERROR_DB.getLabel());
        }
        gameEventTemp = bizGameSystemDao.selectTbGameEvent(gameEventTemp.getId());
        GameEvent gameEvent = new GameEvent();
        gameEvent.setId(gameEventTemp.getId());
        gameEvent.setName(gameEventTemp.getName());
        gameEvent.setGameSystem(gameEventTransfer.getGameSystemById(reqGroupNumAndRankNum.getGameSystemType()));
        if (gameEventTemp.getCurrentRoundId().intValue() == -1) {
            respGameRoundAndGameTeam.setIsFinish((byte) 1);
        }
        respGameRoundAndGameTeam.setIsArrange((byte) 0);
        respGameRoundAndGameTeam.setLimitNum(gameEventTemp.getTeamLimitNum());
        respGameRoundAndGameTeam.setGameEventId(gameEventTemp.getId());
        respGameRoundAndGameTeam.setCurrentTeamNum(gameEventTemp.getTeamLimitNum()-gameEventTemp.getInventoryLevel());


        List temp = gameRoundService.createGameRound(gameEventTemp);        //创建轮次
        if (null == temp || temp.size() == 0) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID.getLabel());
        }
        respGameRoundAndGameTeam.setGameRoundList(temp);
        PageObj<List<GameTeam>> pageObj =  this.gameTeamByGameEvent(gameEventTemp, 0, Constants.DEFAULT_PAGE_SIZE);
        if (pageObj.getTotal() > 0) {
            respGameRoundAndGameTeam.setGameTeamList(pageObj.getItems());
        }else {
            respGameRoundAndGameTeam.setGameTeamList(null);
        }
        logger.info("混合赛分组成功,当前混合赛ID：{} ", tbGameEvent.getId());
        return APIResponse.returnSuccess(respGameRoundAndGameTeam);
    }

    @Override
    public APIResponse<RespGameRoundAndGameTeam> gameRoundAndGameTeam(Integer gameEventId) throws Exception {
        RespGameRoundAndGameTeam respGameRoundAndGameTeam = new RespGameRoundAndGameTeam();
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        GameEvent gameEvent = new GameEvent();
        BeanUtils.copyProperties(gameEvent, tbGameEvent);
        respGameRoundAndGameTeam.setStartTime(tbGameEvent.getStartTime().getTime());
        respGameRoundAndGameTeam.setEndTime(tbGameEvent.getEndTime().getTime());
        respGameRoundAndGameTeam.setSignStartTime(tbGameEvent.getSignStartTime().getTime());
        respGameRoundAndGameTeam.setSignEndTime(tbGameEvent.getSignEndTime().getTime());
        respGameRoundAndGameTeam.setCurTime(new Date().getTime());
        respGameRoundAndGameTeam.setLimitNum(tbGameEvent.getTeamLimitNum());
        respGameRoundAndGameTeam.setGameEventId(gameEventId);
        respGameRoundAndGameTeam.setCurrentTeamNum(tbGameEvent.getTeamLimitNum()-tbGameEvent.getInventoryLevel());
        if (tbGameEvent.getCurrentRoundId().intValue() == -1) {
            respGameRoundAndGameTeam.setIsFinish((byte) 1);
        }

        if (GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED.getId() == tbGameEvent.getGameSystemType().intValue() && tbGameEvent.getTeamGroupNum().intValue() < 1) {
            respGameRoundAndGameTeam.setGameRoundList(null);
            respGameRoundAndGameTeam.setIsArrange((byte) 1);
        }else {
            respGameRoundAndGameTeam.setIsArrange((byte) 0);
            respGameRoundAndGameTeam.setGameRoundList(gameRoundService.createGameRound(tbGameEvent));  //创建轮次
        }
        PageObj<List<GameTeam>> pageObj =  this.gameTeamByGameEvent(tbGameEvent, 0, Constants.DEFAULT_PAGE_SIZE);
        if (null!=pageObj && null!=pageObj.getItems()) {
            respGameRoundAndGameTeam.setGameTeamList(pageObj.getItems());
        }else {
            respGameRoundAndGameTeam.setGameTeamList(null);
        }
        return APIResponse.returnSuccess(respGameRoundAndGameTeam);
    }

    @Override
    public PageObj<List<GameTeam>> gameTeamByGameEventId(Integer gameEventId, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
        return this.gameTeamByGameEvent(bizGameSystemDao.selectTbGameEvent(gameEventId), pageNum, pageSize);
    }

    @Override
    public PageObj<List<GameTeam>> gameTeamByGameEvent(TbGameEvent event, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
        List<GameTeam> result = null;
        int total = 0;
        if (null!=event && null!=event.getId()) {
            List<TbGameEventTeam> tbGameEventTeamList = bizGameSystemDao.selectTbGameEventTeamByGameEventId(event.getId(), pageNum,
                    (gameEventTransfer.getGameCategoryById(event.getGameCategoryType().intValue()).getMinNum() == 2 && gameEventTransfer.getGameCategoryById(event.getGameCategoryType().intValue()).getMaxNum() == 2) ? pageSize * 2 : pageSize, GameConstants.IS_NOT_DELETE);
            if (null!=tbGameEventTeamList && tbGameEventTeamList.size() > 0) {
                result = gameScheduleService.tbGameTeamTransferGameTeam(event, tbGameEventTeamList, event.getGameTeamType());
                return PageObj.create(total, pageNum, pageSize, result);
            }
        }
        return PageObj.create(total, pageNum, pageSize, result);
    }

    @Override
    public APIResponse clubGameEventList(Integer clubId, Integer pageNum, Integer pageSize, Integer uid) throws InvocationTargetException, IllegalAccessException {
        List<Integer> uIds = baseService.getManageByClubId(clubId);
        RespClubGameEventListAndAuth andAuth = new RespClubGameEventListAndAuth();
        if (null != uIds && uIds.contains(uid)) {
            andAuth.setIsAuth(true);
            List<GameEvent> result = new ArrayList<>();
            int total = bizGameSystemDao.countTbGameEventByClubIdNotGameType(clubId, (byte)GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_SCENE.getId());
            if (total == 0) {
                andAuth.setPageObj(PageObj.create(0, pageNum, pageSize, null));
            }else {
                List<TbGameEvent> list = bizGameSystemDao.selectTbGameEventByClubIdNotGameType(clubId, (byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_SCENE.getId(), pageNum, pageSize);
                if (null != list && list.size() > 0) {
                    for (TbGameEvent tbGameEvent : list) {
                        GameEvent gameEvent = officialGameCache.getGameEvent(tbGameEvent.getId());
                        gameEvent.setCreateTime(tbGameEvent.getCreateTime().getTime());
                        gameEvent.setCurTime(new Date().getTime());
                        result.add(gameEvent);
                    }
                }
                andAuth.setPageObj(PageObj.create(total, pageNum, pageSize, result));
            }
            return APIResponse.returnSuccess(andAuth);
        }
        return APIResponse.returnFail("非俱乐部管理员,没有权限查看");



        /*
        List<TbGameClubOfficial> msg = bizGameSystemDao.queryTbGameOfficialClubList(clubId, null);
        if (null == msg || msg.size()<1) {
            andAuth.setIsAuth(false);
            andAuth.setPageObj(PageObj.create(0, pageNum, pageSize, null));
        }else {
            andAuth.setIsAuth(true);


        }
        */
    }


    @Override
    public APIResponse<RespGameEventDetail> gameEventDetail(Integer gameEventId, Integer uid) {
        RespGameEventDetail result = new RespGameEventDetail();
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (tbGameEvent != null && tbGameEvent.getId() != 0) {
            try {
                BeanUtils.copyProperties(result, tbGameEvent);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            Gson gson = new Gson();
            result.setGameSystem(gameEventTransfer.getGameSystemById(tbGameEvent.getGameSystemType().intValue()));
            result.setGameCategory(gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()));
            result.setGameGradeLevel(gameEventTransfer.getGameGradeLevelById(tbGameEvent.getCategoryId(), tbGameEvent.getGameGradeLevelType().intValue()));
            result.setCurrentTeamNum(tbGameEvent.getTeamLimitNum()-tbGameEvent.getInventoryLevel());
            result.setMultiMediaType(gson.fromJson(tbGameEvent.getMultiMedia(), MultiMedia.class));
            if (uid!=null) {
                List<Integer> clubIds = baseService.queryMyClubIds(uid);    //用户所在俱乐部id集合,用户具有特殊权限的俱乐部id
                List<TbGameEventTeam> teams = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEventId, null, null, null);
                if (null !=teams && teams.size() >0) {
                    if (tbGameEvent.getGameEventType().byteValue() != GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId()) {  //
                        for (TbGameEventTeam team : teams) {
                            if (tbGameEvent.getGameTeamType() == GameConstants.TEAM_TYPE_PERSON) {//个人
                                if (team.getUid() == uid) {
                                    result.setIsJoinAccess((byte) 1);
                                    result.setIsJoin((byte) 1);
                                    result.setIsForfeit(team.getIsForfeit());
                                    break;
                                }
                            }else if (tbGameEvent.getGameTeamType() == GameConstants.TEAM_TYPE_CLUB) { //俱乐部
                                if (null!=clubIds&&clubIds.size() >0 && clubIds.contains(team.getClubId())) {
                                    result.setIsJoinAccess((byte) 1);
                                    result.setIsJoin((byte) 1);
                                    result.setIsForfeit(team.getIsForfeit());
                                    break;
                                }

                            }else {
                            }
                        }
                    } else { //积分赛.没有弃权

                        for (TbGameEventTeam team : teams) {
                            if (tbGameEvent.getGameTeamType() == GameConstants.TEAM_TYPE_PERSON) {//个人
                                if (team.getUid().intValue() == uid.intValue()) {
                                    result.setIsJoinAccess((byte) 1);
                                    result.setIsJoin((byte) 1);
                                    break;
                                }
                            }else if (tbGameEvent.getGameTeamType() == GameConstants.TEAM_TYPE_CLUB) { //俱乐部
                                if (null!=clubIds&&clubIds.size() >0 && clubIds.contains(team.getClubId())) {
                                    result.setIsJoinAccess((byte) 1);
                                    result.setIsJoin((byte) 1);
                                    break;
                                }

                            }else {
                            }
                        }
                    }
                }
            }
            GameEventHost gameEventHost = new GameEventHost();
            gameEventHost.setType(tbGameEvent.getType());
            gameEventHost.setHostName(tbGameEvent.getManagerName());
            if (GameConstants.CLUB_CREATE == tbGameEvent.getType()) {
                gameEventHost.setClubId(tbGameEvent.getClubId());
            }
            TbGameCommonParameter icon = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                    GameConstants.BASE_CONFIG_KEY_OFFICIAL_HOST_ICON);
            Image image = new Image();
            image.setImageUrl(icon.getParameterValue());
            gameEventHost.setImage(image);
            result.setGameEventHost(gameEventHost);
            List<Integer> ids= new ArrayList<>();
            ids.add(tbGameEvent.getPlaceId());
            result.setPlaceInfo(baseService.queryPlaceInfoMsgList(ids).get(tbGameEvent.getPlaceId()));
            if (null!=tbGameEvent.getComplementeTime()) {
                result.setCoverTime(tbGameEvent.getComplementeTime().getTime());
            }
        }
        return APIResponse.returnSuccess(result);
    }

    @Override
    public APIResponse<List<GameRound>> gameGroundList(Integer gameEventId, Integer uid) throws InvocationTargetException, IllegalAccessException {

        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        List<TbGameRound> list = bizGameSystemDao.selectTbGameRoundByGameEventIdAndGenerateNotCur(gameEventId);
        if (ObjectUtil.isObjectEmpty(gameEvent, list) || list.size() < 1) {
            return APIResponse.returnSuccess(null);
        }
        List<GameRound> result = new ArrayList<>();
        List<TbUserGameSchedule> userGameSchedules = bizGameSystemDao.queryTbUserGameScheduleByUid(gameEventId, uid);
        List<Integer> uidTemp1 = new ArrayList<>();
        Map<Integer, TbUserGameSchedule> userGameScheduleMap = new HashMap<>();
        for (TbUserGameSchedule temp1 : userGameSchedules) {
            uidTemp1.add(temp1.getGameScheduleId());
            userGameScheduleMap.put(temp1.getGameScheduleId(), temp1);
        }
        for (TbGameRound tbGameRound : list) {
            GameRound gameRound = officialGameCache.getGameRound(tbGameRound.getId());
            List<GameSchedule> temp = userGameScheduleList(tbGameRound.getId(), gameEvent, uidTemp1, userGameScheduleMap);
            if (null!=temp && temp.size()>0) {
                gameRound.setUserScheduleList(this.queryScheduleIdByGameRoundIdAndUid(uidTemp1, gameEventId, temp, uid));
                gameRound.setGameScheduleList(temp);
                result.add(gameRound);
            }
        }
        return APIResponse.returnSuccess(result);
    }

    @Override
    public List<GameSchedule> gameSchedule(Integer gameRoundId, Integer gameEventId) {
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        return this.gameScheduleList(gameRoundId, gameEvent);
    }

    @Override
    public List<GameSchedule> gameScheduleList(Integer gameRoundId, TbGameEvent gameEvent) {

        List<TbGameSchedule> tbGameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameRoundId, GameConstants.PAGE_NUM_DEFAULT, 100);  //默认取100为最大值

        List<GameSchedule> result = new ArrayList<>();
        for (TbGameSchedule tbGameSchedule : tbGameScheduleList) {
            try {
                result.add(officialGameCache.getGameSchedule(tbGameSchedule.getId(), gameEvent.getGameTeamType()));
            } catch (Exception e) {
                logger.error("gameScheduleList officialGameCache.getGameSchedule is failed. e:", e);
            }
        }

        return result;
    }

    @Override
    public List<GameSchedule> userGameScheduleList(Integer gameRoundId, TbGameEvent gameEvent, List<Integer> userScheduleIds, Map<Integer, TbUserGameSchedule> userGameScheduleMap) {
        List<TbGameSchedule> tbGameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameRoundId, GameConstants.PAGE_NUM_DEFAULT, 100);  //默认取100为最大值
        List<GameSchedule> result = new ArrayList<>();
        for (TbGameSchedule tbGameSchedule : tbGameScheduleList) {
            try {
                GameSchedule getGameSchedule = officialGameCache.getGameSchedule(tbGameSchedule.getId(), gameEvent.getGameTeamType());
                if (null!=userScheduleIds && null!=userGameScheduleMap && userScheduleIds.contains(tbGameSchedule.getId())) {
                    if (null!=userGameScheduleMap.get(tbGameSchedule.getId()).getRecordAuth()) {
                        getGameSchedule.setRecordAuth(userGameScheduleMap.get(tbGameSchedule.getId()).getRecordAuth());
                    }
                    if (null!=userGameScheduleMap.get(tbGameSchedule.getId()).getIsAccess()) {
                        getGameSchedule.setIsAccess(userGameScheduleMap.get(tbGameSchedule.getId()).getIsAccess());
                    }
                }
                result.add(getGameSchedule);
            } catch (Exception e) {
                logger.error("gameScheduleList officialGameCache.getGameSchedule is failed. e:", e);
            }
        }
        return result;
    }

    @Override
    public RespGameEventData gameEventData(Integer gameEventId, Integer pageNum, Integer pageSize) {
        RespGameEventData respGameEventData =  null;

        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);

        if (gameEvent == null || 0 == gameEvent.getCurrentRoundId()) {
            return respGameEventData;
        }

        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventIdAndGenerate(gameEvent.getId());

        logger.info("gameEventData:"+ gameEvent.getGameSystemType()+" gameEvent id:"+gameEvent.getId());

        if (null == tbGameRoundList || tbGameRoundList.size() < 1) {
            return respGameEventData;
        }

        try {
            respGameEventData = new RespGameEventData();
            respGameEventData.setCategoryId(gameEvent.getCategoryId());
            respGameEventData.setGameEventId(gameEvent.getId());
            respGameEventData.setGameSystemId(gameEvent.getGameSystemType().intValue());
            respGameEventData.setGameCategoryType(gameEvent.getGameCategoryType());

            Integer roundId = 0;
            TbGameRound currentTbGameRound = null;
            for (TbGameRound tbGameRound : tbGameRoundList) {
                if (gameEvent.getCurrentRoundId().equals(tbGameRound.getId())) {
                    currentTbGameRound = tbGameRound;
                    break;
                }

                roundId = tbGameRound.getId();
            }

            // 淘汰赛
            if (GameSystemConfigEnum.CONFIG_GAME_TYPE_WASHED.getId() == gameEvent.getGameSystemType().intValue()) {
                respGameEventData.setGameScheduleList(getGameScheduleByGameRound(gameEvent, tbGameRoundList));
            } else if (GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED.getId() == gameEvent.getGameSystemType().intValue()) {

                Integer currentTeams = bizGameSystemDao.countTbGameEventTeamByGameEventId(gameEvent.getId());
                int roundNum = GameUtils.circleRoundNum((double) (currentTeams % gameEvent.getTeamGroupNum() + currentTeams / gameEvent.getTeamGroupNum()));

                List<GameSchedule> gameScheduleList;
                List<GameTeam> gameTeamList = new ArrayList<>();
                List<GameSchedule> gameSchedules = new ArrayList<>();
                if ((null!=currentTbGameRound && currentTbGameRound.getRoundStatus().intValue() > roundNum)|| -1 == gameEvent.getCurrentRoundId()) {
                    for (TbGameRound tbGameRound : tbGameRoundList) {
                        if (tbGameRound.getRoundStatus().intValue() == roundNum) {
                            respGameEventData.setGameRoundScoreList(bizGameSystemDao.selectTbGameRoundScoreByGameRoundId(tbGameRound.getId(), pageNum, pageSize));
                            gameScheduleList = gameScheduleList(tbGameRound.getId(), gameEvent);
                            for (GameSchedule gameSchedule : gameScheduleList) {
                                gameTeamList.add(gameSchedule.getHomeGameTeam());
                                if (ObjectUtil.isNotObjectEmpty(gameSchedule.getAwayGameTeam())) {
                                    gameTeamList.add(gameSchedule.getAwayGameTeam());
                                }
                            }
                        } else if (tbGameRound.getRoundStatus().intValue() > roundNum) {
                            gameSchedules.addAll(getGameScheduleByGameRound(gameEvent, tbGameRound));
                        }
                    }

                    respGameEventData.setGameTeamList(gameTeamList);
                    respGameEventData.setGameScheduleList(gameSchedules);
                    logger.info("gameEventData gameEventId:" + gameEventId + " gameSchedules:" + gameSchedules + " CONFIG_GAME_TYPE_MIXED.");
                } else {
                    gameScheduleList = gameScheduleList(roundId, gameEvent);
                    for (GameSchedule gameSchedule : gameScheduleList) {
                        gameTeamList.add(gameSchedule.getHomeGameTeam());
                        gameTeamList.add(gameSchedule.getAwayGameTeam());
                    }
                    respGameEventData.setGameTeamList(gameTeamList);
                    logger.info("gameEventData gameEventId:" + gameEventId + " roundId:" + roundId + " CONFIG_GAME_TYPE_MIXED.");
                    respGameEventData.setGameRoundScoreList(bizGameSystemDao.selectTbGameRoundScoreByGameRoundId(roundId, pageNum, pageSize));
                }

            } else {
                // 其他循环 和  瑞士(等位) , 队伍数目始终一致
                respGameEventData.setGameTeamList(gameScheduleService.tbGameTeamTransferGameTeam(gameEvent, bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEvent.getId(), pageNum, pageSize, GameConstants.IS_NOT_DELETE), gameEvent.getGameTeamType()));
                List<TbGameRoundScore> scores = bizGameSystemDao.selectTbGameRoundScoreByGameRoundId(roundId, pageNum, pageSize);
                if(gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                        && gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
                    scores.clear();
                    List<TbGameRoundScore> scoreTemp = bizGameSystemDao.selectTbGameRoundScoreByGameRoundId(roundId, pageNum, pageSize);
                    for (int j=0;j<scoreTemp.size();j+=2) {
                        scores.add(scoreTemp.get(j));
                    }
                }
                respGameEventData.setGameRoundScoreList(scores);
            }

            logger.info("gameEventData  gameEventId:" + gameEventId + " respGameEventData:" + respGameEventData.toString());
        }catch (Exception e) {
            logger.error("gameEventData is failed. e:", e);
        }
        if (gameEvent.getCurrentRoundId() == -1) {
            List<TbGameEventScore> tbGameEventScores = bizGameSystemDao.queryTbGameEventScoreList(gameEvent.getId());
            if (tbGameEventScores.size()>0 && null!=respGameEventData.getGameRoundScoreList()) {
                List<TbGameRoundScore> temp = respGameEventData.getGameRoundScoreList();
                Map<Integer, Double> rankScore = new HashMap<>();
                for (TbGameEventScore tbGameEventScore:tbGameEventScores) {
                    rankScore.put(tbGameEventScore.getGameEventTeamId(),
                            new BigDecimal(tbGameEventScore.getOriginalScore() + tbGameEventScore.getOpponentScore()/10.0 + tbGameEventScore.getSmallScore()/100.0).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                for (TbGameRoundScore tbGameRoundScore : temp) {
                    tbGameRoundScore.setScore(rankScore.get(tbGameRoundScore.getGameEventTeamId()));
                }
                Collections.sort(temp, new Comparator<TbGameRoundScore>() {   //按轮次的先后排序,id最大的为最后一轮
                    public int compare(TbGameRoundScore o1, TbGameRoundScore o2) {
                        return o2.getScore().compareTo(o1.getScore());
                    }
                });
                respGameEventData.setGameRoundScoreList(temp);
            }
        }
        return respGameEventData;
    }

    @Override
    public APIResponse<PageObj<List<RespOfficialGameTeam>>> placeScoreRankList(Integer gameEventId, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (null == tbGameEvent) {
            return APIResponse.returnFail("赛事不存在");
        }
        if (0 != tbGameEvent.getParentId().intValue()) {
            return APIResponse.returnFail("非官方场馆赛,无排名信息");
        }
        logger.info("获取官方赛的用户排名列表,当前混合赛ID：{} ", tbGameEvent.getId());
        int total = 0;
        List<RespOfficialGameTeam> result = null;
        List<TbGameEventTeam> tbGameTeams = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEventId, null);  //取出是所有的
        if (null != tbGameTeams && tbGameTeams.size() > 0) {
            total = tbGameTeams.size();
            if (tbGameTeams.size() > (pageNum+1)*pageSize) {
                tbGameTeams = tbGameTeams.subList(pageNum*pageSize, (pageNum+1)*pageSize);
            }else if (tbGameTeams.size() > pageNum*pageSize && tbGameTeams.size() <= (pageNum+1)*pageSize) {
                tbGameTeams = tbGameTeams.subList(pageNum*pageSize, tbGameTeams.size());
            }else {
                tbGameTeams = null;
            }
            result = this.tbGameEventTeamToRespOfficialGameTeam(tbGameTeams);
        }
        return APIResponse.returnSuccess(PageObj.create(total,pageNum,pageSize,result));
    }

    /**
     * 将TbGameEventTeam转换为RespOfficialGameTeam;
     *
     * */
    private List<RespOfficialGameTeam> tbGameEventTeamToRespOfficialGameTeam(List<TbGameEventTeam> tbGameTeams) throws InvocationTargetException, IllegalAccessException {
        if (null == tbGameTeams || tbGameTeams.size() == 0) {
            return null;
        }
        List<RespOfficialGameTeam> result = new ArrayList<>();
        List<Integer> uIds = new ArrayList<>();
        List<Integer> clubIds = new ArrayList<>();
        for (TbGameEventTeam vDefinedGameTeam : tbGameTeams) {
            if (GameConstants.TEAM_TYPE_PERSON == vDefinedGameTeam.getType().byteValue()) {
                uIds.add(vDefinedGameTeam.getUid());
            }else if (GameConstants.TEAM_TYPE_CLUB == vDefinedGameTeam.getType().byteValue()){
                clubIds.add(vDefinedGameTeam.getClubId());
            }else {
            }
        }
        Map<Integer, RespClubPlainInfo> mapClubIdMap = baseService.queryClubMsg(clubIds);
        Map<Integer, RespUserInfoBase> mapUidMap = baseService.queryUserMsg(uIds);
        int i=0;
        for (TbGameEventTeam vDefinedGameTeam : tbGameTeams) {
            RespOfficialGameTeam gameTeam = new RespOfficialGameTeam();
            gameTeam.setId(vDefinedGameTeam.getId());
            List<User> users = new ArrayList<>();
            gameTeam.setType(vDefinedGameTeam.getType());
            gameTeam.setIsForfeit(vDefinedGameTeam.getIsForfeit());
            gameTeam.setIsJoin((byte) (vDefinedGameTeam.getIsDelete()==1?0:1));
            gameTeam.setIsJoinAccess(vDefinedGameTeam.getIsJoinAccess());
            if (GameConstants.TEAM_TYPE_CLUB == vDefinedGameTeam.getType().byteValue()) {
                Club club = new Club();
                if (null !=  mapClubIdMap.get(vDefinedGameTeam.getClubId()) && mapClubIdMap.get(vDefinedGameTeam.getClubId()).getClubId()>0) {
                    BeanUtils.copyProperties(club,  mapClubIdMap.get(vDefinedGameTeam.getClubId()));
                }
                gameTeam.setClub(club);
            }else if (GameConstants.TEAM_TYPE_PERSON == vDefinedGameTeam.getType().byteValue()){
                User user = new User();
                if (null != mapUidMap && null !=  mapUidMap.get(vDefinedGameTeam.getUid()) && mapUidMap.get(vDefinedGameTeam.getUid()).getUid()>0) {
                    BeanUtils.copyProperties(user,  mapUidMap.get(vDefinedGameTeam.getUid()));
                }
                user.setScore(vDefinedGameTeam.getScore());
                users.add(user);
                gameTeam.setUserList(users);

            }else {
            }
            i++;
            result.add(gameTeam);
        }
        return result;
    }

    @Override
    public APIResponse<?> placeGameEventList(Integer gameEventId) throws InvocationTargetException, IllegalAccessException {
        List<TbGameEvent> tbGameEvents = bizGameSystemDao.selectTbGameEventByParentId(gameEventId);
        if (null != tbGameEvents && tbGameEvents.size() > 0) {
            List<GameEvent> result = new ArrayList<>();
            Set<Integer> placeIds = new HashSet<>();
            for (TbGameEvent tbGameEvent : tbGameEvents) {
                placeIds.add(tbGameEvent.getPlaceId());
            }
            Map<Integer, PlaceInfo> map = baseService.queryPlaceInfoMsgList(new ArrayList<Integer>(placeIds));
            for (TbGameEvent tbGameEvent : tbGameEvents) {
                GameEvent gameEvent = new GameEvent();
                BeanUtils.copyProperties(gameEvent, tbGameEvent);
                if (null!=map && map.size() > 0) {
                    gameEvent.setPlaceInfo(map.get(tbGameEvent.getPlaceId()));
                }
                GameEventHost gameEventHost = new GameEventHost();
                gameEvent.setGameEventHost(gameEventHost);
                gameEvent.setCurrentTeamNum(tbGameEvent.getTeamLimitNum()-tbGameEvent.getInventoryLevel());
                result.add(gameEvent);
            }
            return APIResponse.returnSuccess(result);
        }
        return APIResponse.returnSuccess(null);
    }

    @Override
    public APIResponse<PageObj<List<RespOfficialGameEvent>>> searchGameEventList(ReqSearchGameEvent reqSearchGameEvent, Integer uid) throws InvocationTargetException, IllegalAccessException {
        List<RespOfficialGameEvent> respOfficialGameEvents = new ArrayList<>();
        List<TbGameEvent> tbGameEvents = bizGameSystemDao.selectTbGameEventByPlaceIdAndCategoryId(reqSearchGameEvent.getCategoryId(), reqSearchGameEvent.getCityId(),
                reqSearchGameEvent.getDistrictId(), reqSearchGameEvent.getPlaceId());

        int total = 0;
        if (null == tbGameEvents || tbGameEvents.size() < 1) {
            return APIResponse.returnSuccess(PageObj.create(total, reqSearchGameEvent.getPageNo(), reqSearchGameEvent.getPageSize(), respOfficialGameEvents));
        }
        total = tbGameEvents.size();


        if (tbGameEvents.size() > reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()+1)) {
            tbGameEvents = tbGameEvents.subList(reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()), reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()+1));
        }else if (tbGameEvents.size() > reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()) && tbGameEvents.size() <= reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()+1)) {
            tbGameEvents = tbGameEvents.subList(reqSearchGameEvent.getPageSize()*(reqSearchGameEvent.getPageNo()), tbGameEvents.size());
        }else {
            tbGameEvents = null;
        }
        if (null == tbGameEvents) {
            respOfficialGameEvents = null;
            return APIResponse.returnSuccess(PageObj.create(total, reqSearchGameEvent.getPageNo(), reqSearchGameEvent.getPageSize(), respOfficialGameEvents));
        }

        List<Integer> gameEventIds = new ArrayList<>();
        for (TbGameEvent tbGameEvent : tbGameEvents) {
            gameEventIds.add(tbGameEvent.getId());
        }
        Map<Integer, List<GameEvent>> gameEventListMap = this.gameEventListMap(uid, gameEventIds, 1, GameConstants.GAME_SCHEDULE_NUM, reqSearchGameEvent);
        //封装活动信息
        for (TbGameEvent tbGameEvent : tbGameEvents) {
            RespOfficialGameEvent officialGameEvent = new RespOfficialGameEvent();
            GameEvent gameEvent = officialGameCache.getGameEvent(tbGameEvent.getId());
            gameEvent.setCurTime(new Date().getTime());
            officialGameEvent.setGameEvent(gameEvent);
            if (null != gameEventListMap && gameEventListMap.size() > 0) {
                if (null!=gameEventListMap.get(tbGameEvent.getId())) {
                    officialGameEvent.setGameEventList(gameEventListMap.get(tbGameEvent.getId()));
                }
            }
            respOfficialGameEvents.add(officialGameEvent);
        }
        return APIResponse.returnSuccess(PageObj.create(total, reqSearchGameEvent.getPageNo(), reqSearchGameEvent.getPageSize(), respOfficialGameEvents));
    }

    /**
     * 对官方赛中的排位赛,根据条件进行筛选
     *
     * 注意:小球类个人参加的赛事,和大球类个人参加的赛事不一样的; 小球类是个人参加的赛事,而大球类是自己所在俱乐部发布的就可以
     *
     * */
    @Override
    public Map<Integer, List<GameEvent>> gameEventListMap(Integer uid, List<Integer> gameEventIds, Integer pageNum, Integer pageSize, ReqSearchGameEvent reqSearchGameEvent) throws InvocationTargetException, IllegalAccessException {
        Map<Integer, List<GameEvent>> result = new HashMap<>();
        List<TbGameEvent> tbGameEvents = bizGameSystemDao.selectTbGameEventByParentIds(gameEventIds);
        if (null==tbGameEvents || tbGameEvents.size() < 1) {
            return result;
        }
        List<Integer> userJoinedGameEventIds = this.userGameEventIds(uid, reqSearchGameEvent.getCategoryId());      //用户报名参加的赛事(大球类,或者小球类)
        List<Integer> userClubGameEventIds = this.userClubPublishGameEventIds(uid, reqSearchGameEvent.getCategoryId());  //用户在该栏目下所有俱乐部创办的赛事
        boolean isFlag;
        for (TbGameEvent tbGameEvent : tbGameEvents) {
            isFlag = false;
            GameEvent gameEvent = officialGameCache.getGameEvent(tbGameEvent.getId());
            if (reqSearchGameEvent.getIsMe()) { //本人报名
                if (null!=userJoinedGameEventIds && userJoinedGameEventIds.contains(tbGameEvent.getId())) {
                    isFlag = true;
                }
            }else { //本人未报
                if (tbGameEvent.getIsVisible().intValue() == GameConstants.IS_NOT_DELETE.intValue()) {  //只是本俱乐部不可见
                    if (null!=userClubGameEventIds && userClubGameEventIds.contains(tbGameEvent.getId())) {
                        isFlag = true;
                    }
                }else {  //所有人可见
                        isFlag = true;
                }
            }
            if (isFlag) {
                List<GameEvent> gameEvents = result.get(tbGameEvent.getParentId());
                if (null == gameEvents || gameEvents.size() < 1) {
                    gameEvents = new ArrayList<>();
                }
                if (null!=userJoinedGameEventIds && userJoinedGameEventIds.size()>0) {
                    if (userJoinedGameEventIds.contains(tbGameEvent.getId())) {
                        gameEvent.setIsJoin((byte) 1);
                    }
                }
                gameEvent.setCurrentTeamNum(tbGameEvent.getTeamLimitNum()-tbGameEvent.getInventoryLevel());
                gameEvent.setCurTime(new Date().getTime());
                gameEvents.add(gameEvent);
                result.put(tbGameEvent.getParentId(), gameEvents);
            }
        }
        for (Integer key : result.keySet()) {
            List<GameEvent> list = (List<GameEvent>)result.get(key);
            List<GameEvent> temp = new ArrayList<>();
            if (null!=list && list.size()>0) {
                for (GameEvent gameEvent : list) {
                    Byte flag = GameConstants.GAME_EVENT_ZERO;
                    if (GameConstants.GAME_EVENT_PRE == reqSearchGameEvent.getStatus()) {
                        if (new Date(gameEvent.getSignStartTime()).after(new Date())) {
                            flag = GameConstants.GAME_EVENT_PRE;
                        }
                    }else if (GameConstants.GAME_EVENT_SIGN == reqSearchGameEvent.getStatus()) {
                        if (new Date(gameEvent.getSignStartTime()).before(new Date()) && new Date(gameEvent.getSignEndTime()).after(new Date())) {
                            flag = GameConstants.GAME_EVENT_SIGN;
                        }
                    }else if (GameConstants.GAME_EVENT_START == reqSearchGameEvent.getStatus()) {
                        if (new Date(gameEvent.getSignEndTime()).before(new Date()) && new Date(gameEvent.getEndTime()).after(new Date())) {
                            flag = GameConstants.GAME_EVENT_START;
                        }
                    }else if (GameConstants.GAME_EVENT_END == reqSearchGameEvent.getStatus()){
                        if (new Date(gameEvent.getEndTime()).before(new Date())) {
                            flag = GameConstants.GAME_EVENT_END;
                        }
                    }else {
                    }
                    if (flag.intValue() != reqSearchGameEvent.getStatus().intValue()) {
                        temp.add(gameEvent);
                    }

                }
            }
            list.removeAll(temp);
            if (list.size()<1) {
                list = null;
            }
            result.put(key, list);
        }
        return result;
    }

    @Override
    public List<Integer> userGameEventIds(Integer uid,  Integer categoryId) {
        Set<Integer> ids = new HashSet<>();

        List<TbGameEventTeam> list = null;
        if (categoryId.intValue() > 0) {
            list = bizGameSystemDao.selectMyTbGameEventTeam(uid, null, GameConstants.TEAM_TYPE_PERSON);          //报名单位是用户
        }else {
            //足球    篮球,以俱乐部单位参赛,只需考虑当时,代表队三种角色的俱乐部
            if (categoryId.equals(GameConstants.CATEGORY_ID_FOOTBALL) || categoryId.equals(GameConstants.CATEGORY_ID_BASKETBALL)) {       //注意大小球的区别
                List<Integer> clubIds = baseService.queryMyClubIds(uid);
                if (null!=clubIds && clubIds.size()>0) {
                    list = bizGameSystemDao.selectMyTbGameEventTeam(null, clubIds, GameConstants.TEAM_TYPE_CLUB);   //报名单位是俱乐部
                }
            }else{
                list = bizGameSystemDao.selectMyTbGameEventTeam(uid, null, GameConstants.TEAM_TYPE_PERSON);          //报名单位是用户
            }
        }
        if (null != list && list.size() >0) {
            for (TbGameEventTeam tb : list) {
                ids.add(tb.getGameEventId());
            }
            return new ArrayList<Integer>(ids);
        }
        return null;
    }

    @Override
    public List<Integer> userClubPublishGameEventIds(Integer uid, Integer categoryId) {
        Set<Integer> ids = new HashSet<>();
        List<Integer> clubIds = baseService.queryMyClubListByCategoryId(uid, categoryId);   //该栏目下所有俱乐部
        List<TbGameEvent> list = bizGameSystemDao.selectTbGameEventByClubId(clubIds);       //获取这些俱乐部发布的赛事
        if (null != list && list.size() >0) {
            for (TbGameEvent tb : list) {
                ids.add(tb.getId());
            }
            return new ArrayList<Integer>(ids);
        }
        return null;
    }

    @Override
    public APIResponse inviteUserByMobile(Integer gameEventId, String mobile, Integer uid) throws InvocationTargetException, IllegalAccessException {
        RespUserInfoBase respUserInfoBase = baseService.queryUserMsgByMobile(mobile);
        if (null == respUserInfoBase || null == respUserInfoBase.getUid()) {
            return APIResponse.returnFail(ErrorEnum.ERROR_USER_NOT_EXIST.getId(), ErrorEnum.ERROR_USER_NOT_EXIST.getLabel());
        }
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (null == tbGameEvent) {
            return APIResponse.returnFail("赛事不存在");
        }
        if(uid.equals(respUserInfoBase.getUid())) {
            return APIResponse.returnFail(ErrorEnum.ERROR_USER_DOUBLE_JOIN.getId(), ErrorEnum.ERROR_USER_DOUBLE_JOIN.getLabel());
        }
        if (tbGameEvent.getGameTeamType().intValue() == GameConstants.IS_NOT_DELETE.intValue() && tbGameEvent.getIsVisible().intValue() == GameConstants.IS_NOT_DELETE.intValue()) {
            if (!baseService.isJoinedClub(tbGameEvent.getClubId(), uid)) {
                return APIResponse.returnFail(ErrorEnum.ERROR_USER_NOT_CLUB_MEM.getId(), ErrorEnum.ERROR_USER_NOT_CLUB_MEM.getLabel());
            }
            if (!baseService.isJoinedClub(tbGameEvent.getClubId(), respUserInfoBase.getUid())) {
                return APIResponse.returnFail(ErrorEnum.ERROR_USER_NOT_CLUB_MEM.getId(), ErrorEnum.ERROR_USER_NOT_CLUB_MEM.getLabel());
            }
        }
        List<TbGameEventTeam> teamList = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEventId, GameConstants.IS_NOT_DELETE);
        if (null != teamList) {
            for (TbGameEventTeam tbGameEventTeam : teamList) {
                if (tbGameEventTeam.getUid().equals(respUserInfoBase.getUid()) || tbGameEventTeam.getUid().equals(uid)) {
                    return APIResponse.returnFail(ErrorEnum.ERROR_USER_DOUBLE_JOIN.getId(), ErrorEnum.ERROR_USER_DOUBLE_JOIN.getLabel());
                }
            }
        }
        User user = new User();
        BeanUtils.copyProperties(user, respUserInfoBase);
        return APIResponse.returnSuccess(user);
    }

    @Override
    public List<Integer> queryScheduleIdByGameRoundIdAndUid(List<Integer> uidTemp1, Integer gameEventId, List<GameSchedule> temp, Integer uid) {
        List<Integer> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(uidTemp1) && CollectionUtils.isNotEmpty(temp)) {
            List<Integer> uidTemp2 = new ArrayList<>();
            for (GameSchedule temp2 : temp) {
                uidTemp2.add(temp2.getId());
            }
            for (Integer integer : uidTemp2) {
                if (uidTemp1.contains(integer)) {
                    result.add(integer);
                }
            }
        }
        return result;
    }

    @Override
    public List<GameEvent> getResGameEventsByClubId(Integer clubId) throws InvocationTargetException, IllegalAccessException {
        List<TbGameEvent> tbGameEvents = bizGameSystemDao.selectTbGameEventByClubId(clubId, 0, 3);
        if (null != tbGameEvents && tbGameEvents.size() > 0) {
            List<GameEvent> resGameEvents = new ArrayList<>();
            for (TbGameEvent tbGameEvent : tbGameEvents) {
               resGameEvents.add(officialGameCache.getGameEvent(tbGameEvent.getId()));
            }
            return resGameEvents;
        }
        return null;
    }


    public RespGameSystemAndGameCategory generateGameSystemAndGameCategory(List<GameCategoryConfigEnum> categories, List<GameSystemConfigEnum> systems,
                                                                            List<GameGradeLevelConfigEnum> gradeLevels, List<PayTypeEnum> payTypes, Integer categoryId){
        RespGameSystemAndGameCategory result = new RespGameSystemAndGameCategory();
        List<GameSystem> systemList = new ArrayList<>();
        List<GameCategory> categoryList = new ArrayList<>();
        List<GameGradeLevel> gameGradeLevels = new ArrayList<>();
        List<PayTypeModel> payTypeList = new ArrayList<>();
        for (GameCategoryConfigEnum gameCategoryConfigEnum : categories) {
            GameCategory gameCategory = new GameCategory();
            gameCategory.setGameCategoryType(gameCategoryConfigEnum.getId());
            gameCategory.setName(gameCategoryConfigEnum.getLabel());
            categoryList.add(gameCategory);
        }
        for (GameSystemConfigEnum gameSystemConfigEnum : systems) {
            GameSystem gameSystem = new GameSystem();
            gameSystem.setGameSystemType(gameSystemConfigEnum.getId());
            gameSystem.setName(gameSystemConfigEnum.getLabel());
            systemList.add(gameSystem);
        }
        for (GameGradeLevelConfigEnum gradeLevelConfigEnum : gradeLevels) {
            gameGradeLevels.add(gameEventTransfer.getGameGradeLevelById(categoryId, gradeLevelConfigEnum.getId()));
        }
        for (PayTypeEnum payTypeEnum : payTypes) {
            PayTypeModel payType = new PayTypeModel();
            payType.setPayType((byte) payTypeEnum.getId());
            payType.setType((byte) payTypeEnum.getType());
            payType.setName(payTypeEnum.getLabel());
            payTypeList.add(payType);
        }
        result.setCategoryList(categoryList);
        result.setSystemList(systemList);
        result.setGradeLevelList(gameGradeLevels);
        result.setPayList(payTypeList);
        return result;
    }

    public List<RespGameSystem> generateGameSystemAndGameCategoryV2(Map<GameSystemConfigEnum, List<GameCategoryConfigEnum>> params){
        List<RespGameSystem> result = new ArrayList<>();
        for (Map.Entry<GameSystemConfigEnum, List<GameCategoryConfigEnum>> entry : params.entrySet()) {
            RespGameSystem v2 = new RespGameSystem();

            GameSystemConfigEnum g = entry.getKey();
            v2.setGameSystemType(g.getId());
            v2.setName(g.getLabel());

            List<GameCategory> categoryList = new ArrayList<>();
            List<GameCategoryConfigEnum> c = entry.getValue();
            for (GameCategoryConfigEnum gameCategoryConfigEnum : c) {
                GameCategory gameCategory = new GameCategory();
                gameCategory.setGameCategoryType(gameCategoryConfigEnum.getId());
                gameCategory.setName(gameCategoryConfigEnum.getLabel().substring(0,2));
                Integer minValue = 2;
                Integer maxValue = 1024;
                if(gameCategoryConfigEnum.equals(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V5)){
                    minValue = 5;
                    maxValue = 5;
                }else if(gameCategoryConfigEnum.equals(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V6)){
                    minValue = 6;
                    maxValue = 6;
                }else if(gameCategoryConfigEnum.equals(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V7)){
                    minValue = 7;
                    maxValue = 7;
                }else if(gameCategoryConfigEnum.equals(GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8)){
                    minValue = 8;
                    maxValue = 8;
                }
                gameCategory.setMinNum(minValue);
                gameCategory.setMaxNum(maxValue);
                categoryList.add(gameCategory);
            }
            v2.setGameCategories(categoryList);
            v2.setMinNum(2);
            v2.setMaxNum(1024);
            if (g.getId() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
                v2.setMinNum(8);
                v2.setMaxNum(8);
            }
            result.add(v2);
        }
        return result;
    }

    private Map<Integer, TbGameScheduleAddendum> listChangeMap(List<TbGameScheduleAddendum> tbGameScheduleAddendumList){
        Map<Integer, TbGameScheduleAddendum> map = new HashMap<Integer, TbGameScheduleAddendum>();

        for(TbGameScheduleAddendum tbGameScheduleAddendum: tbGameScheduleAddendumList) {
            map.put(tbGameScheduleAddendum.getGameScheduleId(), tbGameScheduleAddendum);
        }

        return map;
    }

    private List<GameSchedule> getGameScheduleByGameRound(TbGameEvent gameEvent, List<TbGameRound> tbGameRoundList) {
        List<GameSchedule> gameScheduleList = new ArrayList<GameSchedule>();


        for (TbGameRound tbGameRound : tbGameRoundList) {
            if (-1 == gameEvent.getCurrentRoundId().intValue() || tbGameRound.getId() <= gameEvent.getCurrentRoundId()) {
                gameScheduleList.addAll(gameScheduleList(tbGameRound.getId(), gameEvent));
            }
        }

        return gameScheduleList;
    }

    private List<GameSchedule> getGameScheduleByGameRound(TbGameEvent gameEvent, TbGameRound tbGameRound) {
        List<GameSchedule> gameScheduleList = new ArrayList<GameSchedule>();
        gameScheduleList.addAll(gameScheduleList(tbGameRound.getId(), gameEvent));
        return gameScheduleList;
    }

    @Override
    public RespPersonalGameEventDetail selectPersonalGameEventDetail(Integer gameEventId,Integer uid) {
        RespPersonalGameEventDetail personalGameEventDetail = new RespPersonalGameEventDetail();
        try {
            GameEvent gameEvent= officialGameCache.getGameEvent(gameEventId);
            if(null != gameEvent){
                //更新报名人数
                TbGameEvent tbGameEvent = tbGameEventMapper.selectByPrimaryKey(gameEventId);
                if(null != tbGameEvent) {
                    gameEvent.setCurrentTeamNum(tbGameEvent.getTeamLimitNum() - tbGameEvent.getInventoryLevel());
                    personalGameEventDetail.setGameDesc(tbGameEvent.getGameDesc());

                    //结束掉比赛开始但报名人数未满的比赛
                    Date currentTime = new Date();
                    if (tbGameEvent.getIsDelete().byteValue() == GameConstants.IS_NOT_DELETE.byteValue() && tbGameEvent.getStartTime().before(currentTime) && tbGameEvent.getInventoryLevel() > 0
                            && tbGameEvent.getCurrentRoundId() >= 0) {
                        tbGameEvent.setCurrentRoundId(-1);
                        List<Integer> uids = new ArrayList<>();
                        uids.add(tbGameEvent.getUid());
                        gameMsgPush.unNormalEnd(tbGameEvent, uids);
                        tbGameEventMapper.updateByPrimaryKeySelective(tbGameEvent);
                    }

                    //赛事状态
                    gameEvent.setCurTime(currentTime.getTime());
                    if (tbGameEvent.getCurrentRoundId().byteValue() == GameConstants.GAME_EVENT_ZERO.byteValue()) {
                        personalGameEventDetail.setGameStatus(GameConstants.GAME_EVENT_END);
                    } else {
                        if (currentTime.getTime() < tbGameEvent.getStartTime().getTime()) {
                            personalGameEventDetail.setGameStatus(GameConstants.GAME_EVENT_SIGN);
                        } else {
                            personalGameEventDetail.setGameStatus(GameConstants.GAME_EVENT_START);
                        }
                    }
                }
                //用户是否已经加入
                if(null != uid) {
                    ReqSignResult req = new ReqSignResult();
                    req.setGameId(gameEventId);
                    req.setUid(uid);
                    RespGameResult respGameResult = gameSignUpService.checkSign(req).getData();
                    if (null != respGameResult && null != respGameResult.getStatus()) {
                        gameEvent.setIsJoin(respGameResult.getStatus().byteValue());
                    }
                }else{
                    gameEvent.setIsJoin((byte)0);
                }
                personalGameEventDetail.setGameEvent(gameEvent);
                List<TbGameRound> tbGameRoundList  = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
                if(null != tbGameRoundList && tbGameRoundList.size() > 0){
                    TbGameRound gameRound = tbGameRoundList.get(0);
                    List<TbGameSchedule> gameScheduleList  = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameRound.getId(), 0, 1);
                    if(null != gameScheduleList && gameScheduleList.size() > 0){
                        TbGameSchedule tbGameSchedule = gameScheduleList.get(0);
//                        officialGameCache.delGameSchedule(tbGameSchedule.getId());
                        GameSchedule gameSchedule = officialGameCache.getGameSchedule(tbGameSchedule.getId(), GameConstants.TEAM_TYPE_PERSON);
                        if(null != gameSchedule){
                            personalGameEventDetail.setGameSchedule(gameSchedule);
                        }
                    }
                }
                //单打还是双打
                Boolean isTeam = true;
                Integer gameCategoryType = gameEvent.getGameCategory().getGameCategoryType();
                if(null != gameCategoryType){
                    if(gameCategoryType == GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY.getId() ||
                            gameCategoryType == GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_MALE_ONLY.getId() ||
                            gameCategoryType == GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_FEMALE_ONLY.getId()){
                        isTeam = false;
                    }
                }
                personalGameEventDetail.setIsTeam(isTeam);
            }
        }catch (Exception e){
            logger.error("selectPersonalGameEventDetail fail",e);
        }
        return personalGameEventDetail;
    }

    @Override
    public void lockScoreAndEndPersonalGameEvents() {
        Date seventDate = DateUtils.addNDay(new Date(), -7);
        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        criteria.andTypeEqualTo(GameConstants.PERSONAL_CREATE);
        criteria.andInventoryLevelEqualTo(0);
        criteria.andCurrentRoundIdGreaterThan(0);
        criteria.andStartTimeLessThanOrEqualTo(seventDate);
        example.setPage(new Page(0,50));
        List<TbGameEvent> gameEventList = tbGameEventMapper.selectByExample(example);
        if(null != gameEventList && gameEventList.size() > 0){
            for(TbGameEvent tbGameEvent : gameEventList){
                List<TbGameRound> tbGameRoundList  = bizGameSystemDao.selectTbGameRoundByGameEventId(tbGameEvent.getId());
                if(null != tbGameRoundList && tbGameRoundList.size() > 0) {
                    TbGameRound gameRound = tbGameRoundList.get(0);
                    List<TbGameSchedule> gameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameRound.getId(), 0, 1);
                    if (null != gameEventList && gameEventList.size() > 0) {
                        TbGameSchedule tbGameSchedule = gameScheduleList.get(0);
                        TbGameEvent gameEvent = new TbGameEvent();
                        TbGameSchedule gameSchedule = new TbGameSchedule();
                        gameSchedule.setId(tbGameSchedule.getId());
                        if (tbGameSchedule.getStatus() == GameConstants.RECORD_WAIT) {
                            gameEvent.setCurrentRoundId(-1);
                        } else if (tbGameSchedule.getStatus() == GameConstants.RECORD_WAIT_SURE || tbGameSchedule.getStatus() == GameConstants.RECORD_SECOND_WAIT_SURE) {
                            gameEvent.setCurrentRoundId(-1);
                            gameSchedule.setStatus(GameConstants.RECORD_SUCCESS);
                            tbGameScheduleMapper.updateByPrimaryKeySelective(gameSchedule);
                        }
                        tbGameEventMapper.updateByExampleSelective(gameEvent, example);

                        //比赛结束，通知参赛人员
                        TbGameEventTeamExample eventTeamExample = new TbGameEventTeamExample();
                        TbGameEventTeamExample.Criteria criteria_team = eventTeamExample.createCriteria();
                        criteria_team.andGameEventIdEqualTo(tbGameEvent.getId());
                        List<TbGameEventTeam> tbGameEventTeamList = tbGameEventTeamMapper.selectByExample(eventTeamExample);
                        if(null != tbGameEventTeamList && tbGameEventTeamList.size() > 0){
                            List<Integer> uids = new ArrayList<>();
                            for(TbGameEventTeam tbGameEventTeam : tbGameEventTeamList){
                                uids.add(tbGameEventTeam.getUid());
                            }
                            gameMsgPush.pushGameFinishPushMsgToUser(tbGameEvent,uids);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void endPersonalGameEvents() {
        Date currentTime = new Date();
        TbGameEvent gameEvent = new TbGameEvent();
        gameEvent.setCurrentRoundId(-1);

        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        criteria.andTypeEqualTo(GameConstants.PERSONAL_CREATE);
        criteria.andInventoryLevelGreaterThan(0);
        criteria.andStartTimeLessThanOrEqualTo(currentTime);
        criteria.andCurrentRoundIdNotEqualTo(-1);
        example.setPage(new Page(0,50));
        List<TbGameEvent> tbGameEventList = tbGameEventMapper.selectByExample(example);
        if(null != tbGameEventList && tbGameEventList.size() > 0 ){
            List<Integer> uids = new ArrayList<>();
            for(TbGameEvent tbGameEvent : tbGameEventList){
                uids.clear();
                uids.add(tbGameEvent.getUid());
                if(uids.size() > 0 && null != tbGameEvent){
                    gameMsgPush.unNormalEnd(tbGameEvent,uids);
                }
            }
        }

        tbGameEventMapper.updateByExampleSelective(gameEvent,example);
    }

    @Override
    public RespScoreMsg getRecordResultMessage(Integer gameEventId,Integer uid) {
        List<TbGameRound> tbGameRoundList  = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
        RespScoreMsg msg = new RespScoreMsg();
        String score;
        int record_uid = 0;
        Boolean isVisible = false;
        Boolean isMe = false;
        Byte myTeamType = 0;
        Boolean isMyTeam = false;
        List<Byte> recordTeamType = new ArrayList<>();
        List<Integer> recordUids = new ArrayList<>();
        if(null != tbGameRoundList && tbGameRoundList.size() > 0){
            TbGameRound gameRound = tbGameRoundList.get(0);
            List<TbGameSchedule> gameScheduleList  = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameRound.getId(), 0, 1);
            if(null != gameScheduleList && gameScheduleList.size() > 0){
                TbGameSchedule tbGameSchedule = gameScheduleList.get(0);
                try {
                    GameSchedule gameSchedule = officialGameCache.getGameSchedule(tbGameSchedule.getId(), GameConstants.TEAM_TYPE_PERSON);
                    if(null != gameSchedule){
                        List<VDefinedGameSchedule> currentGameSchedules = bizGameSystemDao.selectVDefinedGameScheduleById(gameSchedule.getId());
                        for(VDefinedGameSchedule  vDefinedGameSchedule : currentGameSchedules){
                            if(null != vDefinedGameSchedule.getRecordScore() && vDefinedGameSchedule.getFinalScore().trim().equals(vDefinedGameSchedule.getRecordScore().trim())){
                                score = vDefinedGameSchedule.getFinalScore();
                                record_uid = vDefinedGameSchedule.getUid();
                                recordTeamType.add(vDefinedGameSchedule.getType());
                                myTeamType = vDefinedGameSchedule.getType();
                                msg.setScore(score);
                                msg.setRecordTime(vDefinedGameSchedule.getUpdateTime());
                                msg.setStatus(vDefinedGameSchedule.getStatus());
                                break;
                            }
                        }
                        for(VDefinedGameSchedule  vDefinedGameSchedule : currentGameSchedules){
                            recordUids.add(vDefinedGameSchedule.getUid().intValue());
                            if(vDefinedGameSchedule.getUid().intValue() == uid.intValue() && vDefinedGameSchedule.getType() == myTeamType){
                                isMyTeam = true;
                                break;
                            }
                        }
                        if(recordUids.contains(uid)){
                            isVisible = true;
                        }
                        if(record_uid == uid.intValue()){
                            isMe = true;
                        }
                        RespUserInfoDetail userMsg = baseService.queryUserMsg(record_uid);
                        if(null != userMsg){
                            msg.setNickName(userMsg.getNickName());
                        }
                    }
                }catch (Exception e){
                    logger.error("getRecordResultMessage fail",e);
                }
            }
        }
        msg.setIsTeamMate(isMyTeam);
        msg.setIsMe(isMe);
        msg.setIsVisible(isVisible);
        return msg;
    }

    @Override
    public int userRecordScoreV2(Integer uid, ReqRecordGameScheduleResult reqId) {
        return gameScheduleService.userRecordScoreV2(uid, reqId);
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateOpponentV2(ReqUpdateOpponent reqUpdateOpponent) {
        try{
            // 获取轮次列表
            List<TbGameRound> roundList = bizGameSystemDao.selectTbGameRoundByGameEventId(reqUpdateOpponent.getGameEventId());
            if (roundList == null || roundList.size() == 0) {
                logger.info("updateOpponentV2 GameEventId not exist");
                return;
            }

            TbGameRound tbGameRound = roundList.get(0);

            logger.info("updateOpponentV2 tbGameRound roundId:"+tbGameRound.getId()+" isEnd:"+tbGameRound.getIsEnd());
            if (tbGameRound.getIsEnd() == 0) {
                boolean flag = false;
                Map<Integer, Integer> map = Collections.emptyMap();
                TbGameEvent tbGameEvent =  tbGameEventMapper.selectByPrimaryKey(tbGameRound.getGameEventId());
                if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                        && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
                    flag = true;
                    map = gameRoundService.gameTeamIdTransferTeamIdNew(tbGameRound.getGameEventId());
                    logger.info("updateOpponentV2 map:"+ map);
                }


                //一个赛程对应一个新的teamIds
                Map<Integer, List<Integer>> scheduleTeams = reqUpdateOpponent.getScheduleTeams();

                logger.info("updateOpponentV2 scheduleTeams:"+scheduleTeams);

                List<TbGameSchedule> tbGameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(tbGameRound.getId());

                logger.info("updateOpponentV2 roundId:"+tbGameRound.getId()+" tbGameScheduleList:"+tbGameScheduleList);
                if (null == tbGameScheduleList || tbGameScheduleList.size() == 0) {
                    return;
                }

                List<Integer> scheduleids = new ArrayList<>();
                for(TbGameSchedule tbGameSchedule : tbGameScheduleList){
                    scheduleids.add(tbGameSchedule.getId());
                }

                logger.info("updateOpponentV2 scheduleids:"+ scheduleids);

                //删除旧的对战记录，重新生成
                bizGameSystemDao.deleteTbGameScheduleAddendumByGameScheduleId(scheduleids);

                //利用 scheduleTeams的遍历为接下来提供用户映射关系\
                for (Integer scheduleId : scheduleTeams.keySet()){
                    List<Integer> teamIdList = scheduleTeams.get(scheduleId);

                    TbGameScheduleAddendum tbGameScheduleAddendum,tbGameScheduleAddendum1;
                    for (int i = 0; i<teamIdList.size(); i++) {
                        tbGameScheduleAddendum = new TbGameScheduleAddendum();
                        tbGameScheduleAddendum1 = new TbGameScheduleAddendum();
                        tbGameScheduleAddendum.setGameScheduleId(scheduleId);
                        tbGameScheduleAddendum1.setGameScheduleId(scheduleId);
                        tbGameScheduleAddendum.setEventTeamId(teamIdList.get(i));
                        //设置主/客场
                        if (i == 0) {
                            tbGameScheduleAddendum.setType(GameConstants.GAME_HOME);
                            tbGameScheduleAddendum1.setType(GameConstants.GAME_HOME);
                        } else {
                            tbGameScheduleAddendum.setType(GameConstants.GAME_AWAY);
                            tbGameScheduleAddendum1.setType(GameConstants.GAME_AWAY);
                        }

                        logger.info("是否双打:{}, 队伍集合:{}", flag);

                        if (flag) {
                            if (teamIdList.get(i) == 0){
                                logger.info("轮次id:{}出现对手轮空", scheduleId);
                                tbGameScheduleAddendum1.setEventTeamId(0);
                            }else {
                                tbGameScheduleAddendum1.setEventTeamId(map.get(teamIdList.get(i)));
                            }
                            bizGameSystemDao.insertTbGameScheduleAddendum( tbGameScheduleAddendum1);
                        }

                        bizGameSystemDao.insertTbGameScheduleAddendum(tbGameScheduleAddendum);
                    }
                    gameCacheDao.delGameScheduleFromCache(scheduleId);

                }

                //更新等位制比赛的轮次冗余信息
                if (tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getId()) {
                    gameScheduleService.updateSwissRound(tbGameRound, flag);
                }
            }

        }catch (Exception e) {
            logger.info("updateOpponentV2 exception:", e);
        }

    }

    @Override
    public Map<Integer, List<RespClubAbstract>> getUserClubMsg(Integer uid) {
        Map<Integer, List<RespClubAbstract>> result = new HashMap<>();
        List<RespClubPlainInfo> clubs = baseService.getMyManageClubs(uid);
        if (CollectionUtils.isNotEmpty(clubs)) {
            for (RespClubPlainInfo club : clubs) {
                RespClubAbstract ab = new RespClubAbstract();
                ab.setClubId(club.getClubId());
                ab.setClubName(club.getClubName());
                List<RespClubAbstract> temp = result.get(club.getClubTypeId());
                if (CollectionUtils.isEmpty(temp)) {
                    temp = new ArrayList<>();
                }
                temp.add(ab);
                result.put(club.getClubTypeId(), temp);
            }
        }
        return result;
    }

    @Override
    public String recordResultForPersonalAgainst(Integer uid, ReqRecordGameScheduleResult req) {
        //借助rdis特性处理并发
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getPersonalGameEventRecordScore(req.getGameEventId()));
        long recordFlag = myRedisTemplate.setnx(redisKey);
        if (recordFlag == 0) {
            myRedisTemplate.delteKey(redisKey);
            return "比分录入处理中,请不要重复操作";
        }

        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(req.getGameEventId());
        List<VDefinedGameSchedule> currentGameSchedules = bizGameSystemDao.selectVDefinedGameScheduleById(req.getGameScheduleId());
        int flag = validateRecordAuthForPersonalGame(req, tbGameEvent, currentGameSchedules);
        if (flag > 0) {
            return RecordScoreErrorEnum.getMsgById(flag);
        }

        VDefinedGameSchedule vTemp = new VDefinedGameSchedule();

        boolean isUser = false, isDoubleRecord = false;
        Byte myTeamType = 0;
        Integer teamMateUid = 0;

        //用户id
        List<Integer> uids = new ArrayList<>();
        for(VDefinedGameSchedule  vDefinedGameSchedule : currentGameSchedules){
            uids.add(vDefinedGameSchedule.getUid());
        }

        //把roundId放进去，以便结束比赛
        req.setGameRoundId(currentGameSchedules.get(0).getGameRoundId());

        List<Byte> recordTeamType = new ArrayList<>();
        for (VDefinedGameSchedule  vDefinedGameSchedule : currentGameSchedules) {
            if ((gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2 &&
                    gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2)) {
                if (null != vDefinedGameSchedule.getRecordScore()) {
                    recordTeamType.add(vDefinedGameSchedule.getType());
                }
                if (vDefinedGameSchedule.getUid().intValue() == uid.intValue()) {
                    myTeamType = vDefinedGameSchedule.getType();
                    vTemp = vDefinedGameSchedule;
                    if(null != vDefinedGameSchedule.getRecordScore() && req.getScores().length() >0){
                        isDoubleRecord = true;
                    }
                    isUser = true;
                }
            }else {
                if (vDefinedGameSchedule.getUid().intValue() == uid.intValue()) {
                    isUser = true;
                    if (null != vDefinedGameSchedule.getRecordScore()) {
                        if(req.getScores().length() >0){
                            isDoubleRecord = true;
                        }
                    }
                    vTemp = vDefinedGameSchedule;
                    break;
                }
            }
        }

        //去掉用户自己的id
        if(uids.contains(uid)){
            uids.remove(uid);
        }

        //本队队友uid
        for(VDefinedGameSchedule  vDefinedGameSchedule : currentGameSchedules){
            if(myTeamType.byteValue() == vDefinedGameSchedule.getType().byteValue() && uid.intValue() != vDefinedGameSchedule.getUid()){
                teamMateUid = vDefinedGameSchedule.getUid();
            }
        }


        if (!isUser) {            //校验用户合法性;
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_7.getLabel();
        }
        if (isDoubleRecord) {   //校验用户是否再次已经录入
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_8.getLabel();
        }
        if (recordTeamType.contains(myTeamType) && null != req.getScores() && req.getScores().length() > 0) {  //队友已经录入
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_12.getLabel();
        }

        TbGameScheduleAddendum addendum = new TbGameScheduleAddendum();
        addendum.setId(vTemp.getId());
        if (null !=req.getScores() && req.getScores().length() > 0) {
            addendum.setRecordScore(req.getScores());
            tbGameScheduleAddendumMapper.updateByPrimaryKeySelective(addendum);
        }

        boolean firstRecord = false,firstComfim = false,secondComfim = false,recordFinal = false,isFail = false;
        if(vTemp.getStatus() == GameConstants.RECORD_WAIT_SURE){
            if(req.getIsSure()){ //我方录入了一次比分，对手同意了
                firstComfim = true;
                recordFinal = true;
            }else{ //我方录入了一次比分，对手不同意，并且录入一次比分
                secondComfim = true;
            }
        }else if(vTemp.getStatus() == GameConstants.RECORD_SECOND_WAIT_SURE){
            if(req.getIsSure()){ //我方录入一次比分，对手不同意并录入了一次比分，我方同意
                recordFinal = true;
            }else{
                isFail = true;
            }
        }else{
            firstRecord = true;
        }

        //更新比分并向用户推送消息
        this.updateRecordScore(tbGameEvent,uid,uids,teamMateUid,req, firstRecord, firstComfim, secondComfim, recordFinal, isFail);
        String result = "录入成功";
        if(isFail){
            result = "比分无效";
        }
        myRedisTemplate.delteKey(redisKey);
        return result;
    }

    public boolean updateRecordScore(TbGameEvent tbGameEvent,Integer uid,List<Integer> uids,Integer teamMateUid,ReqRecordGameScheduleResult req,Boolean firstRecord,Boolean firstComfim,Boolean secondComfim,Boolean recordFinal,Boolean isFail) {
        TbGameScheduleExample example = new TbGameScheduleExample();
        TbGameScheduleExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(req.getGameScheduleId());
        List<TbGameSchedule> tbGameScheduleList = tbGameScheduleMapper.selectByExample(example);
        ReqFinishGameEvent reqFinishGameEvent = new ReqFinishGameEvent();
        reqFinishGameEvent.setGameEventId(req.getGameEventId());
        reqFinishGameEvent.setCurrentRoundId(req.getGameRoundId());
        RespUserInfoDetail userMsg = baseService.queryUserMsg(uid);
        String inputerName = "";
        if(null != userMsg){
            inputerName = userMsg.getNickName();
        }
        if (null != tbGameScheduleList && tbGameScheduleList.size() > 0) {
            TbGameSchedule tbGameSchedule = tbGameScheduleList.get(0);
            if(firstRecord){ //第一个人录入,推送消息给对手全体队员
                tbGameSchedule.setStatus(GameConstants.RECORD_WAIT_SURE);
                uids.remove(teamMateUid);
                gameMsgPush.inputScore(tbGameEvent,uids,inputerName,new Date().getTime());
            }
            if(firstComfim || recordFinal){ //比分录入正常结束,通知参赛选手
                tbGameSchedule.setStatus(GameConstants.RECORD_SUCCESS);
                //结束比赛
                logger.info("开始调用结束个人赛接口,比分正确录入");
                this.finishPersonaPersonalGameEvent(reqFinishGameEvent, uid, true);
                uids.add(uid);
            }
            if(secondComfim){ //比分异议 推送给第一次录入比分那一队
                uids.remove(teamMateUid);
                tbGameSchedule.setStatus(GameConstants.RECORD_SECOND_WAIT_SURE);
                gameMsgPush.pushRecordScoreDisputeMsgToUser(req,tbGameEvent,uids,new Date().getTime());
            }
            if(isFail){ //比分无效
                tbGameSchedule.setStatus(GameConstants.RECORD_FAIL);
                //结束比赛
                logger.info("开始调用结束个人赛接口,比分录入无效");
                this.finishPersonaPersonalGameEvent(reqFinishGameEvent, uid, false);
                uids.add(uid);
                //比分录入有争议，比赛结束，通知参赛选手
                gameMsgPush.vitiationScore(tbGameEvent,uids);
            }
            if (null !=req.getScores() && req.getScores().length() > 0) {
                tbGameSchedule.setFinalScore(req.getScores());
            }
            tbGameSchedule.setIsWin(req.getIsWin());
            bizGameSystemDao.updateTbGameSchedule(tbGameSchedule);
            gameCacheDao.delGameScheduleFromCache(req.getGameScheduleId());
            return true;
        }

        return false;
    }

    private int validateRecordAuthForPersonalGame(ReqRecordGameScheduleResult req, TbGameEvent tbGameEvent, List<VDefinedGameSchedule> currentGameSchedules){
        int result = -1;
        if(null == req.getScores() || req.getScores().length() == 0){
            return result;
        }
        boolean isParam= false;
        String[] str = req.getScores().split(":");
        Integer scoreInt1 = Integer.parseInt(str[0]), scoreInt2 = Integer.parseInt(str[1]);
        //比赛未开始，不允许录入比分
        if(new Date().getTime() < tbGameEvent.getStartTime().getTime()){
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_9.getId();
        }
        //不能平局，也就是比分不能一样
        if(scoreInt1.intValue() == scoreInt2.intValue()){
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_13.getId();
        }
        if ((scoreInt1.intValue() > scoreInt2.intValue() && req.getIsWin() == GameConstants.SCHEDULE_WIN) ||
                (scoreInt1.intValue() < scoreInt2.intValue() && req.getIsWin() == GameConstants.SCHEDULE_LOSE) ||
                (scoreInt1.intValue() == scoreInt2.intValue() && req.getIsWin() == GameConstants.SCHEDULE_TIE)) {
            isParam = true;
        }
        if (!isParam) {
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_1.getId();
        }

        if (null!=tbGameEvent.getCurrentRoundId() && tbGameEvent.getCurrentRoundId().intValue() == -1) {
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_2.getId();
        }

        if (null == currentGameSchedules || currentGameSchedules.size() <1 || null == tbGameEvent) {
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_3.getId();
        }
        TbGameSchedule currentSchedule = tbGameScheduleMapper.selectByPrimaryKey(req.getGameScheduleId());
        if (null == currentSchedule || currentSchedule.getIsEnd().equals(GameConstants.IS_DELETE)) {
            return RecordScoreErrorEnum.RECORD_SCORE_LIST_ERROR_5.getId();
        }
        return result;
    }
}
